/*
*
*拦截器
*验证登录，且把response.data数据提取到resp里面
*
*/
(function (win) {
    const instance = axios.create({
            baseURL: '/',
            timeout: 10000,
            headers: {'Content-Type': 'application/json;charset=utf-8'},
        });
    // 添加请求拦截器
    instance.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        return config;
    }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });

    // 添加响应拦截器
    instance.interceptors.response.use(function (response) {
        console.log('---拦截器的响应数据---:', response); // 添加调试信息

        const url = window.location.href;
        console.log(url);

        const code = response.data.code;
        const msg = response.data.msg;


        if (code === 0 && msg === 'NotLogin') {
            if(url.includes("/easyban/login.html")){
                localStorage.removeItem('userInfo')
                return
            }
            // 未登录，重定向到登录页面
            console.log('用户未登录，重定向到登录页面');

            window.location.href = '/easyban/index.html?message=NotLogin';
        } else if (code === 0 && msg === 'NotPower') {
            if(url.includes("/easyban/login.html")){
                window.location.href = '/easyban/index.html?message=Login';
                return
            }
            // 未登录，重定向到登录页面
            console.log('用户没有权限重定向到登录页面');
            window.location.href = '/easyban/index.html?message=NotPower';
        } else if (code === 0 && msg === 'Login') {
            if(url.includes("/easyban/login.html")){
                window.location.href = '/easyban/index.html?message=Login';
            }
        }else {
            //直接返回data里面的数据
            return response.data;
        }
    }, function (error) {
        console.log('err' + error);
        let {message} = error;
        if (message === "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            /*message = "系统接口" + message.substr(message.length - 3) + "异常";*/
            message = "您填写的信息异常，请核对后重新尝试"
        }
        alert(message);
        return Promise.reject(error);
    });
    win.axios = instance;
})(window);


